use serde::Deserialize;
use std::fs;

#[derive(Deserialize)]
struct DbConfig {
    user: String,
    password: String,
    host: String,
    port: u32,
    database: String,
}

#[derive(Deserialize)]
struct MongoConfig {
    user: String,
    password: String,
    host: String,
    port: i32,
}

#[derive(Deserialize, Debug)]
struct AppConfig {
    port: u16,
    ip: String,
}

#[derive(Deserialize)]
pub struct Config {
    app: AppConfig,
    db_mysql: DbConfig,
    db_mongo: MongoConfig,
}

impl Config {
    pub fn new(path: &'static str) -> Self {
        let config = fs::read_to_string(path).unwrap();
        serde_json::from_str(&config).unwrap()
    }

    // 获取端口
    pub fn get_uri(&self) -> String {
        println!("server is running {}:{}", self.app.ip, self.app.port);
        format!("{0}:{1}", self.app.ip, self.app.port)
    }

    /**
     * 获取数据库连接地址
     */
    pub fn get_database_url(&self) -> String {
        format!(
            "mysql://{0}:{1}@{2}:{3}/{4}",
            self.db_mysql.user,
            self.db_mysql.password,
            self.db_mysql.host,
            self.db_mysql.port,
            self.db_mysql.database
        )
    }

    pub fn get_mongo_uri(&self) -> String {
        std::env::var("MONGODB_URI").unwrap_or_else(|_| {
            format!(
                "mongodb://{}:{}@{}:{}",
                self.db_mongo.user, self.db_mongo.password, self.db_mongo.host, self.db_mongo.port
            )
        })
    }
}
